<?php
/**
 * Created by PhpStorm.
 * User: Hushengs
 * Date: 2017/3/4
 * Time: 15:31
 */
include_once dirname(dirname(__FILE__)) . DIRECTORY_SEPARATOR . 'nl_common.func.php';
class nl_assets_fusion
{
    public $message_id='';
    public $dc;
    public function __construct($cp_config=null)
    {
        $this->dc = nl_get_dc(array (
            "db_policy" => NL_DB_WRITE,
            "cache_policy" => NP_KV_CACHE_TYPE_MEMCACHE
        ));
//        $this->dc->db()
        $this->db_obj = new nns_db_class(g_db_host, g_db_username, g_db_password, g_db_name);
        $this->conn = $this->db_obj->nns_db_connect();
        $this->cp_config = $cp_config;
        $this->debug_log = nns_debug_log_class::get_instance();
        $this->debug_log->setlogpath('import_asset_log');

        $this->media_import_module = $this->cp_config['media_replace_mode_one'];
        $this->media_import_comm = $this->cp_config['media_replace_mode_two'];
        $this->media_import_module_v2 = $this->cp_config['media_replace_mode_three'];
    }

    /**
     * 点播影片信息添加、修改
     * @param String 注入来源ID
     * @param array(
     * "assets_category"="分类名"
    svc_item_id=”定价ID” ××××××××××××××基础函数未存
    video_type=”1为直播  0为点播”  *默认为0
    name =”媒资名称”   *必要参数
    sreach_key=” 国医养生馆 青海卫视”  （可以搜索字段)
    view_type =“0为电影 1为连续剧” *默认为0
    director =“导演,导演,….” (可以搜索字段)
    player =“演员,演员,….” (可以搜索字段)
    tag=“情感,动作,……”标签   (可以搜索字段)
    region=“日韩,欧美”地区     (可以搜索字段)
    release_time =“上映时间”    (可以搜索排序字段)
    totalnum =“总集数”  *默认为1
    national =“国别”   (可以搜索字段) ××××××××××××××基础函数未存
    smallpic=”小海报”  ××××××××××××××基础函数未存
    intro =“剧情简介”
    producer =“供片商”  (可以搜索字段)
    adaptor=“编剧”
    point="推荐星级"
    play_role =“角色扮演”  （芒果暂无）
    subordinate_name =“别名”
    english_name =“英文名”
    language =“视频语种”
    caption_language =“字幕语种,字幕语种,”
    initials=“影片名首字母”   (可以搜索字段) ××××××××××××××基础函数未存
    view_len="影片时长（秒）"（芒果暂无）
    copyright_range =“版权期限”
    total_clicks=“总点击” (可以排序字段)  ××××××××××××××基础函数未存
    month_clicks=“月点击”(可以排序字段)  ××××××××××××××基础函数未存
    week_clicks=“周点击”(可以排序字段)  ××××××××××××××基础函数未存
    day_clicks=“日点击”  ××××××××××××××基础函数未存
    copyright=“版权信息”

     *     )
     * @param String 父栏目ID
     * @return video_id 注入后的video_id
     * 			FALSE 注入失败
     */
    public function update_asset($asset_item_id, $params, $parent_category_id = '10000')
    {
        //首先添加媒资入库
        $video_inst = new nns_db_vod_class();

        $video_inst->message_id = $this->message_id;
        $params['asset_source'] = FUSION_FLAG;
        $exists_id = $video_inst->get_video_id_by_import_id(IMPORT_SOURCE, $asset_item_id,$params['asset_source']);


        $params['assets_category'] = trim($params['assets_category']);
        if(strlen($params['assets_category'])<1)
        {
            return false;
        }
        //     获取主媒资的主分类标识
        //     当未传递view_type时根据assets_category一级栏目计算一个
        $params['view_type'] = $this->get_import_vod_view_type($params);
        //引入v2新版
        include_once dirname(dirname(dirname(__FILE__))). "/v2/common.php";
        \ns_core\m_load::load("ns_core.m_config");
        global $g_bk_version_number;
        $category_v2 = get_config_v2('g_category_v2');
        $bk_version_number = ($g_bk_version_number == '1' && $category_v2 == 1)? true : false;
        unset($g_bk_version_number);
        if ($bk_version_number)
        {
            \ns_core\m_load::load("ns_data_model.category.m_category_v2_inout");
            $do_category = array(
                'base_info' => array(
                    'nns_name' => $params['assets_category'],   //栏目名称支持多层目录，多层目录的时候 /分割
                    'nns_import_category_id' => '', //栏目名称支持多层目录，多层目录的时候 /分割
                    'nns_cp_id' => $params['asset_source'],
                    'nns_import_parent_category_id' => '',
                    'nns_video_type' => '0',  //媒资类型  0 点播 | 1 直播
                ),
            );
            $obj_excute = new \m_category_v2_inout();
            $result = $obj_excute->add($do_category);
            if ($result['ret'] != NS_CDS_SUCCE || !is_array($result['data_info']['base_info']) || empty($result['data_info']['base_info']))
            {
                return false;
            }
            $depot_info = array(
                'id' => $result['data_info']['base_info']['nns_depot_id'],
                'category' => $result['data_info']['base_info']['nns_id'],
                'org_id' => $result['data_info']['base_info']['nns_org_id'],
                'name' => $result['data_info']['base_info']['nns_name'],
            );
        }
        else
        {
            if(isset($params['parent_assets_category_id']) && strlen($params['parent_assets_category_id']) > 1)
            {
                $depot_info_parent = $this->set_depot_category($params['parent_assets_category'], 0, substr($params['parent_assets_category_id'], 0,-3));
                $parent_category_id = $depot_info_parent['category'];
            }
            $depot_info = $this->set_depot_category($params['assets_category'], 0, $parent_category_id);
        }


        if (strlen($params["initials"]) == 0)
        {
            $pinyin = nns_controls_pinyin_class::get_pinyin_letter($params['name']);
            $pinyin_length = nns_controls_pinyin_class::$length;
        }
        elseif(strstr($params["initials"],'|'))
        {
            $simplespell = explode('|', $params["initials"]);
            $pinyin = $simplespell[0];
            $pinyin_length = strlen($pinyin);
        }
        else
        {
            $pinyin = $params["initials"];
            $pinyin_length = strlen($pinyin);
        }
        if ($exists_id === FALSE)
        {
            $result = $this->nns_db_vod_add($this->change_spcial_word($params['name']), $params['view_type'], $depot_info['id'], $depot_info['category'], 0, $depot_info['org_id'], NULL, array(
                'director' => $this->change_spcial_word($params['director']),
                'actor' => $this->change_spcial_word($params['player']),
                'show_time' => $params['release_time'],
                'view_len' => intval($params['view_len']),
                'all_index' => intval($params['totalnum']),
                'area' => $this->change_spcial_word($params['region']),
                'eng_name' => $this->change_spcial_word($params['english_name']),
                'screenwriter' => $this->change_spcial_word($params['adaptor']),
                'alias_name' => $this->change_spcial_word($params['subordinate_name']),
                'producer' => $this->change_spcial_word($params['producer']),
                'language' => $this->change_spcial_word($params['language']),
                'nns_keyword' => $this->change_spcial_word($params['sreach_key']),
                'kind' => $this->change_spcial_word($params['tag']),
                'play_role' => $this->change_spcial_word($params['play_role']),
                'text_lang' => $this->change_spcial_word($params['caption_language']),
                'copyright' => $this->change_spcial_word($params['copyright']),
                "config_info" => $params["config_info"],
                "integer_id" => $params["integer_id"],
            ), $this->change_spcial_word($params['intro']), $params['point'], $params['copyright_range'], NULL, $asset_item_id, $pinyin, g_cms_config::get_g_config_value('g_video_audit_enabled'), IMPORT_SOURCE,$pinyin_length,$params['asset_source'],$params['guid']);
            if ($result['ret'] == 0)
            {
                $new_video_id = $result['data']['id'];
            }
            else
            {
                $new_video_id = FALSE;
            }
        }
        else
        {
            $result = $this->nns_db_vod_modify($exists_id, $this->change_spcial_word($params['name']), $params['view_type'], $depot_info['id'], $depot_info['category'], 0, $depot_info['org_id'], NULL, array(
                'director' => $this->change_spcial_word($params['director']),
                'actor' => $this->change_spcial_word($params['player']),
                'show_time' => $params['release_time'],
                'view_len' => intval($params['view_len']),
                'all_index' => intval($params['totalnum']),
                'area' => $this->change_spcial_word($params['region']),
                'eng_name' => $this->change_spcial_word($params['english_name']),
                'screenwriter' => $this->change_spcial_word($params['adaptor']),
                'alias_name' => $this->change_spcial_word($params['subordinate_name']),
                'producer' => $this->change_spcial_word($params['producer']),
                'language' => $this->change_spcial_word($params['language']),
                'nns_keyword' => $this->change_spcial_word($params['sreach_key']),
                'kind' => $this->change_spcial_word($params['tag']),
                'play_role' => $this->change_spcial_word($params['play_role']),
                'text_lang' => $this->change_spcial_word($params['caption_language']),
                'copyright' => $this->change_spcial_word($params['copyright']),
                "config_info" => $params["config_info"],
                "integer_id" => $params["integer_id"],
            ), $this->change_spcial_word($params['intro']), $params['point'], $params['copyright_range'], NULL, $pinyin,$pinyin_length,$params['asset_source']);
            if ($result['ret'] == 0)
            {
                $dc = nl_get_dc(array(
                    'db_policy' => NL_DB_WRITE,
                    'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
                ));
                $dc->open();
                nl_vod::delete_vod_info_by_cache($dc, $exists_id);
                $new_video_id = $exists_id;
            }
            else
            {
                $new_video_id = FALSE;
            }
        }
        return $new_video_id;
    }

    /**
     * 通过导入ID 获取CMS平台ID
     * @param String 来源
     * @param String 来源ID
     * @return string ID
     * 			FALSE 无此ID
     */
    public function get_video_id_by_import_id($import_source, $import_id,$cp_id=null) {

        $str_sql = "select nns_id from nns_vod where " .
            "nns_import_source='{$import_source}' and " .
            "nns_asset_import_id='{$import_id}' and nns_deleted!=1";
        if (strlen($cp_id) < 1)
        {
            $cp_id = 0;
        }
        $str_sql.=" and nns_cp_id='{$cp_id}'";
        $result = $this->db_obj->nns_db_query($str_sql);
        if (is_array($result['data'])) {
            if (count($result['data']) > 0) {
                return $result['data'][0]['nns_id'];
            } else {
                return FALSE;
            }
        }
        return FALSE;
    }

    /**
     * 当且仅当主媒资没有传递view_type字段时，
     * 根据配置以及主媒资的一级栏目
     * 获取主媒资的主分类，如电影、电视剧等计算一个主分类标识
     * @param $request_data 主媒资数据
     * @return 主媒资的主分类
     *  '电影' => 0,
     *	'电视剧' => 1,
     *	'综艺' => 2,
     *	'动漫' => 3,
     *	'音乐' => 4,
     *	'纪实' => 5
     * @author fuyuan.shuai
     * @date 2014-08-19
     */
    private function get_import_vod_view_type($request_data)
    {
        if (strlen($request_data['view_type']) > 0)
        {
            return $request_data['view_type'];
        }

        $category_label_map = array(
            '电影' => 0,
            '电视剧' => 1,
            '综艺' => 2,
            '动漫' => 3,
            '音乐' => 4,
            '纪实' => 5,
            '教育' => 6,
            '体育' => 7,
            '生活' => 8,
            '财经' => 9,
            '微电影' => 10,
            '品牌专区' => 11,
            '广告' => 12,
        );

        if (!is_array($request_data))
        {
            return 0;
        }

        if (isset($request_data["assets_category"]))
        {
            $category_key = $request_data['assets_category'];
            if (isset($category_label_map[$category_key]))
            {
                return $category_label_map[$category_key];
            }
        }

        return 0;
    }

    /**
     * $category_name 栏目名称
     * $parent_id  代码动态创建几级栏目 10000代表一级栏目, 代表二级栏目 ,
     * $$depot_type 0 点播 ,1直播
     */
    public function set_depot_category($category_name, $depot_type = 0, $parent_id = '10000')
    {
        $depot_inst = new nns_db_depot_class();
        $depot_result = $depot_inst->nns_db_depot_info(0, NULL, $depot_type);

        $org_id = $depot_result['data'][0]['nns_org_id'];
        $org_type = $depot_result['data'][0]['nns_org_type'];
        $depot_id = $depot_result['data'][0]['nns_id'];
        $depot_info = $depot_result['data'][0]['nns_category'];
        //加载xml
        $dom = new DOMDocument('1.0', 'utf-8');
        $dom->loadXML($depot_info);
        $category_id_arr = array();
        $categorys = $dom->getElementsByTagName('category');
        foreach ($categorys as $category)
        {
            //栏目名称和栏目父节点同时相同才认为存在该栏目，允许不同栏目级别下面的栏目名称相同
            $parent = $parent_id == '10000' ? 0 : $parent_id;
            //echo $category->getAttribute('name').'-----'.$category_name.'---------'.$category->getAttribute('parent').'-------'.$parent.'<br/>';
            if ($category->getAttribute('name') === $category_name && $category->getAttribute('parent') === (string)$parent)
            {
                $category_id = $category->getAttribute('id');
                return array(
                    'id' => $depot_id,
                    'category' => $category_id,
                    'org_id' => $org_id,
                    'name' => $category->getAttribute('name')
                );
            }
            else
            {
                $category_id_arr[$category->getAttribute('id')] = $category->getAttribute('id');
            }
        }
        //exit('exit');
        $category_parent = $parent_id == 10000 ? 0 : $parent_id;
        $category_id = $parent_id * 1000;
        foreach ($category_id_arr as $key => $val)
        {

            if (strlen($category_id) != strlen($val))
            {
                unset($category_id_arr[$key]);
            }
        }
        //	echo $parent_id;exit;
        for ($i = 1; $i < 1000; $i++)
        {
            $category_id = $category_id + $i;
            if (!array_key_exists((string)$category_id, $category_id_arr))
            {
                break;
            }
        }
        //echo $category_id.'------------';
        //echo $category_parent;exit;
        //$category_parent = substr($category_id,0,strlen($category_id)-3);
        //创建栏目
        $bool = true;

        if ($category_parent != 0)
        {

            foreach ($categorys as $item)
            {
                if ($item->getAttribute("id") === $category_id)
                {
                    $bool = false;
                    break;
                }
            }
            if ($bool)
            {
                //			print_r($category);exit;
                foreach ($categorys as $item)
                {
                    //		 	 	echo $item->getAttribute("id").'---'.$category_parent;
                    //var_dump($item->getAttribute("id"));
                    //var_dump($category_parent);exit;
                    if ($item->getAttribute("id") === (string)$category_parent)
                    {
                        $item_new = $dom->createElement("category");
                        $item_new->setAttribute("id", $category_id);
                        $category_name = str_replace("<", "", $category_name);
                        $category_name = str_replace("/>", "", $category_name);
                        $category_name = str_replace("\"", "", $category_name);
                        $category_name = str_replace("'", "", $category_name);
                        $item_new->setAttribute("name", $category_name);
                        $item_new->setAttribute("parent", $category_parent);
                        //	    	 		echo '<pre>-----';
                        //	    	 		print_r($item_new);exit;
                        $item->appendChild($item_new);
                        break;
                    }
                }
            }
            else
                break;
        }
        else
        {
            foreach ($categorys as $item)
            {
                if ($item->getAttribute("id") === $category_id)
                {
                    $bool = false;
                    break;
                }
            }
            if ($bool)
            {
                $item_new = $dom->createElement("category");
                $item_new->setAttribute("id", $category_id);
                $item_new->setAttribute("name", $category_name);
                $item_new->setAttribute("parent", $category_parent);
                $dom->firstChild->appendChild($item_new);
            }
        }
        $xml_data = $dom->saveXML();
        //修改栏目
        $result = $depot_inst->nns_db_depot_modify('', $xml_data, $org_type, $org_id, $depot_type);

        //修改栏目成功
        if ($result['ret'] == '0')
        {
            return array(
                'id' => $depot_id,
                'category' => $category_id,
                'org_id' => $org_id,
                'name' => $category_name
            );
        }
        return false;
    }

    function change_spcial_word($param)
    {
        switch ($this->spcial_word)
        {
            default :
                $param = str_replace("'", "\'", $param);
                $param = str_replace('"', '\"', $param);
                return $param;
                break;
        }
    }

    /**
     *
     * 修改VOD信息 ...
     * @param string $id vodid GUID
     * @param string $name 名称
     * @param int $view_type 电视剧或电影
     * @param array(4) $catogery 栏目
     * @param int $org_type 机构类型
     * @param string $org_id 机构id
     * @param array(32) $tag CP/SP标记
     * @param array(4) $vod_info 影视信息
     * @param string $summary 简介
     * @param string $remark 备注
     */
    public function nns_db_vod_modify($id, $name, $view_type = 1, $depot_id = null, $depot_detail_id = null, $org_type = 0, $org_id = null, $tag = null, $vod_info = null, $summary = null, $point = null, $copyright_date = null, $remark = null, $nns_pinyin = null, $nns_pinyin_length = '0',$nns_cp_id = null,$nns_integer_id = null) {
//	修改影片信息输入
        foreach ($vod_info as $info_key => $info_value) {
            if ($info_key == 'actor' || $info_key == 'director') {
                $space = false;
            } else {
                $space = true;
            }
            if (!empty($info_value)) {
                $vod_info[$info_key] = np_build_split_string($info_value, '/', $space);
            }
        }

        $result = array();
        if (!isset($id) || !isset($name)) {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod modify param error');
            return $result;
        }
        if (empty($id) || empty($name)) {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod modify param error');
            return $result;
        }

        $str_sql = "select 1 from nns_vod where nns_id='$id'";
        $result = $this->db_obj->nns_db_query($str_sql);
        if ($result [ret] != 0) {
            return $result;
        }
        if (!empty($copyright_date)) {
            $time_str.=",nns_copyright_date='$copyright_date' ";
        }
        $point = (int) $point;
        if ($this->db_obj->num_rows > 0) {
            $str_sql = "update nns_vod set nns_deleted=0, nns_name='$name',nns_pinyin_length='$nns_pinyin_length',nns_view_type=$view_type,nns_depot_id='$depot_id',nns_category_id='$depot_detail_id',nns_point=$point" . $time_str;
            //org
            if ($org_type !== null && $org_type !== '') {
                $org_type = (int) $org_type;
                $str_sql .= ",nns_org_type=$org_type";
            }
            if ($org_id != null) {
                $str_sql .= ",nns_org_id='$org_id'";
            }
            if(strlen($nns_cp_id) > 0)
            {
                $nns_cp_id = FUSION_FLAG;
                $str_sql .= ",nns_cp_id='$nns_cp_id'";
            }
            else
            {
                $str_sql .= ",nns_cp_id='0'";
            }

            /**
             * 新tag存储方式 BY S67
             */
            if (!empty($tag)) {
                if (is_array($tag)) {
                    $len = count($tag);
                    $str_sql .= ",nns_tag = ";
                    $tag_value = '';
                    for ($i = 0; $i < $len; $i++) {
                        if (!empty($tag [$i])) {
                            $tag_value .= $i . ',';
                        }
                    } //for
                    $str_sql .= "'$tag_value'";
                }
            }
            //vod_info
            if (!empty($vod_info)) {
                if (is_array($vod_info)) {
                    if ($vod_info ["director"] !== null) {
                        $str_sql .= ",nns_director='" . $vod_info ["director"] . "'";
                    }
                    if ($vod_info ["actor"] !== null) {
                        $str_sql .= ",nns_actor='" . $vod_info ["actor"] . "'";
                    }
                    if (!empty($vod_info ["show_time"])) {
                        $str_sql .= ",nns_show_time='" . $vod_info ["show_time"] . "'";
                    }
                    if ($vod_info ["view_len"] !== null) {
                        $str_sql .= ",nns_view_len=" . $vod_info ["view_len"];
                    }
                    if ($vod_info ["all_index"] !== null) {
                        $str_sql .= ",nns_all_index=" . $vod_info ["all_index"];
                    }
                    if ($vod_info ["new_index"] !== null) {
                        $str_sql .= ",nns_new_index=" . $vod_info ["new_index"];
                        ;
                    }
                    if ($vod_info ["area"] !== null) {
                        $str_sql .= ",nns_area='" . $vod_info ["area"] . "'";
                    }

                    if ($vod_info ["vod_part"] !== null) {
                        $str_sql .= ",nns_vod_part='" . $vod_info ["vod_part"] . "'";
                    }
                    if ($vod_info ["play_role"] !== null) {

                        $str_sql .= ",nns_play_role='" . $vod_info ["play_role"] . "'";
                    }
                    if ($vod_info ["eng_name"] !== null) {
                        $str_sql .= ",nns_eng_name='" . $vod_info ["eng_name"] . "'";
                    }
                    if ($vod_info ["screenwriter"] !== null) {
                        $str_sql .= ",nns_screenwriter='" . $vod_info ["screenwriter"] . "'";
                    }
                    if ($vod_info ["alias_name"] !== null) {
                        $str_sql .= ",nns_alias_name='" . $vod_info ["alias_name"] . "'";
                    }
                    if ($vod_info ["producer"] !== null) {
                        $str_sql .= ",nns_producer='" . $vod_info ["producer"] . "'";
                    }
                    if ($vod_info ["language"] !== null) {
                        $str_sql .= ",nns_language='" . $vod_info ["language"] . "'";
                    }
                    if ($vod_info ["nns_keyword"] !== null) {
                        $str_sql .= ",nns_keyword='" . $vod_info ["nns_keyword"] . "'";
                    }
                    if (!empty($vod_info ["kind"])) {
                        $str_sql .= ",nns_kind='" . $vod_info ["kind"] . "'";
                    }
                    if (!empty($vod_info ["text_lang"])) {
                        $str_sql .= ",nns_text_lang='" . $vod_info ["text_lang"] . "'";
                    }
                    if (isset($vod_info ["nns_play_count"])) {
                        $str_sql .= ",nns_play_count='" . $vod_info ["nns_play_count"] . "'";
                    }

                    if (isset($vod_info ["copyright"])) {
                        $str_sql .= ",nns_copyright='" . $vod_info ["copyright"] . "'";
                    }
                    if (isset($vod_info ["config_info"])) {
                        $str_sql .= ",nns_conf_info='" . $vod_info ["config_info"] . "'";
                    }
                    if (isset($vod_info ["integer_id"]) && !empty($vod_info ["integer_id"])) {
                        $str_sql .= ",nns_integer_id='" . $vod_info ["integer_id"] . "'";
                    }
                }
            } //vodinfo  end if


            if ($summary != null) {
                $str_sql .= ",nns_summary='$summary'";
            }
            if ($remark != null) {
                $str_sql .= ",nns_remark='$remark'";
            }
            if ($nns_pinyin != null) {
                $str_sql .= ",nns_pinyin='$nns_pinyin'";
            }


            $str_sql .= ",nns_modify_time=now() ";
            $str_sql .= ",nns_state=0 ";
            $str_sql .= ",nns_status=2, nns_action='modify'";
            $str_sql .= " where nns_id='$id'";
            $result = $this->db_obj->nns_db_execute($str_sql);

//			修改相应媒资包，服务包绑定数据
            if ($result["ret"] == 0) {
                if (!empty($vod_info['show_time'])) {
                    $vod_info['year'] = substr(trim($vod_info["show_time"]), 0, 4);
                }
                //	  新增首字母标签类型
                if ($nns_pinyin != null) {
                    $vod_info['initial'] = substr($nns_pinyin, 0, 1);
                }

                $label_inst = new nns_label();
                $label_inst->delete_label(
                    $id, 0
                );
                $label_inst->add_label(
                    $id, 0, $vod_info
                );
            }
        }
        return $result;
    }

    public function nns_db_vod_add(
        $name, $view_type = 1, $depot_id = null, $depot_detail_id = null, $org_type = 0, $org_id = null, $tag = null, $vod_info = null, $summary = null, $point = null, $copyright_date = null, $remark = null, $nns_asset_import_id = null, $nns_pinyin = null, $check = null, $nns_import_source = NULL, $nns_pinyin_length = '0', $nns_cp_id = null,$guid
    ) {
        //	修改影片信息输入
        foreach ($vod_info as $info_key => $info_value) {
            if ($info_key == 'actor' || $info_key == 'director') {
                $space = false;
            } else {
                $space = true;
            }
            if (!empty($info_value)) {
                $vod_info[$info_key] = np_build_split_string($info_value, '/', $space);
            }
        }
        $result = array();
        if (!isset($name)) {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod add param error');
            $this->log->write(__LINE__ . var_export($result, true));
            return $result;
        }
        if (empty($name)) {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod add param error');
            $this->log->write(__LINE__ . var_export($result, true));
            return $result;
        }
        //生成GUID
//        $guid = new Guid ();
//        $id = $guid->toString();
        $id = $guid;
        $check = (int) $check;

        $state = 0;


        //如果是包含媒资注入ID，则表示该影片是媒资注入的
        if ($nns_asset_import_id != null) {
            $state = 2;
        }


        $point = (int) $point;
        $time_key = '';
        $time_value = '';
        if (!empty($copyright_date)) {
            $time_key.=",nns_copyright_date";
            $time_value.=",'$copyright_date'";
        }
        $str_sql = "insert into nns_vod";
        $field = "nns_pinyin_length,nns_id,nns_name,nns_check,nns_state,nns_view_type," .
            "nns_depot_id,nns_category_id,nns_point,nns_asset_import_id" . $time_key;
        $values = "'$nns_pinyin_length','$id','$name',$check,$state,$view_type,'$depot_id'," .
            "'$depot_detail_id',$point,'$nns_asset_import_id'" . $time_value;
        //org
        if ($org_type !== null && $org_type !== '') {
            $org_type = (int) $org_type;
            $field .= ",nns_org_type";
            $values .= ",$org_type";
        }
        if ($org_id != null) {
            $field .= ",nns_org_id";
            $values .= ",'$org_id'";
        }
        if (strlen($nns_cp_id) > 0)
        {
            //$nns_cp_id = intval($nns_cp_id);
            $nns_cp_id=FUSION_FLAG;
            $field .= ",nns_cp_id";
            $values .= ",'$nns_cp_id'";
        }
        else
        {
            $field .= ",nns_cp_id";
            $values .= ",'0'";
        }

        /**
         * 新tag存储方式
         */
        if (!empty($tag)) {
            if (is_array($tag)) {
                $len = count($tag);
                $field .= ",nns_tag ";
                $tag_value = "";
                for ($i = 0; $i < $len; $i++) {
                    if (!empty($tag [$i])) {
                        $tag_value .= $i . ',';
                    }
                } //for
                $values .= ",'$tag_value'";
            }
        }
        //vod_info
        if (!empty($vod_info)) {
            if (is_array($vod_info)) {
                if ($vod_info ["director"] != null) {
                    $field .= ",nns_director";
                    $values .= ",'" . $vod_info ["director"] . "'";
                }
                if ($vod_info ["actor"] != null) {
                    $field .= ",nns_actor";
                    $values .= ",'" . $vod_info ["actor"] . "'";
                }
                if ($vod_info ["show_time"] != null) {
                    $field .= ",nns_show_time";
                    $values .= ",'" . $vod_info ["show_time"] . "'";
                }
                if ($vod_info ["view_len"] != null) {
                    $field .= ",nns_view_len";
                    $values .= "," . $vod_info ["view_len"];
                }
                if ($vod_info ["all_index"] != null) {
                    $field .= ",nns_all_index";
                    $values .= "," . $vod_info ["all_index"];
                }

                if (!empty($vod_info ["new_index"])) {
                    $field .= ",nns_new_index";
                    $values .= "," . $vod_info ["new_index"];
                }
                if (!empty($vod_info ["area"])) {
                    $field .= ",nns_area";
                    $values .= ",'" . $vod_info ["area"] . "'";
                }
                if (!empty($vod_info ["vod_part"])) {
                    $field .= ",nns_vod_part";
                    $values .= ",'" . $vod_info ["vod_part"] . "'";
                }
                if (!empty($vod_info ["play_role"])) {
                    $field .= ",nns_play_role";
                    $values .= ",'" . $vod_info ["play_role"] . "'";
                }
                if (!empty($vod_info ["eng_name"])) {
                    $field .= ",nns_eng_name";
                    $values .= ",'" . $vod_info ["eng_name"] . "'";
                }
                if (!empty($vod_info ["screenwriter"])) {
                    $field .= ",nns_screenwriter";
                    $values .= ",'" . $vod_info ["screenwriter"] . "'";
                }
                if (!empty($vod_info ["alias_name"])) {
                    $field .= ",nns_alias_name";
                    $values .= ",'" . $vod_info ["alias_name"] . "'";
                }
                if (!empty($vod_info ["producer"])) {
                    $field .= ",nns_producer";
                    $values .= ",'" . $vod_info ["producer"] . "'";
                }
                if (!empty($vod_info ["language"])) {
                    $field .= ",nns_language";
                    $values .= ",'" . $vod_info ["language"] . "'";
                }
                if (!empty($vod_info ["nns_keyword"])) {
                    $keyword = $vod_info ["nns_keyword"];
                }

                if (!empty($vod_info ["kind"])) {
                    $field .= ",nns_kind";
                    $values .= ",'" . $vod_info ["kind"] . "'";
                }
                if (!empty($vod_info ["text_lang"])) {
                    $field .= ",nns_text_lang";
                    $values .= ",'" . $vod_info ["text_lang"] . "'";
                }
                if (isset($vod_info ["nns_play_count"])) {
                    $field .= ",nns_play_count";
                    $values .= ",'" . (int) $vod_info["nns_play_count"] . "'";
                    //$str_sql .= ",nns_play_count='" . $vod_info ["nns_play_count"]. "'";
                }

                if (isset($vod_info ["copyright"])) {
                    $field .= ",nns_copyright";
                    $values .= ",'" . $vod_info ["copyright"] . "'";
                    //$str_sql .= ",nns_play_count='" . $vod_info ["nns_play_count"]. "'";
                }
                if (!empty($vod_info ["config_info"])) {
                    $field .= ",nns_conf_info";
                    $values .= ",'" . $vod_info ["config_info"] . "'";
                }
                if (!empty($vod_info ["integer_id"])) {
                    $field .= ",nns_integer_id";
                    $values .= ",'" . $vod_info ["integer_id"] . "'";
                }
            }
        } //vodinfo  end if


        if ($summary != null) {
            $field .= ",nns_summary";
            $values .= ",'$summary'";
        }
        if ($remark != null) {
            $field .= ",nns_remark";
            $values .= ",'$remark'";
        }
        if ($nns_import_source != null) {
            $field .= ",nns_import_source";
            $values .= ",'$nns_import_source'";
        }
        $field .= ",nns_create_time,nns_modify_time,nns_deleted,nns_keyword";
        $values .= ",now(),now()," . NNS_VOD_DELETED_FALSE . ",'$keyword'";

        if ($nns_pinyin != null) {
            $field .=",nns_pinyin";
            $values .=",'$nns_pinyin' ";
        }


        //添加状态和动作

        $field .= ",nns_status,nns_action";
        $values .=",1,'add'";

        // vod
        $str_sql .= "(" . $field . ")values(" . $values . ")";
        $result = $this->db_obj->nns_db_execute($str_sql);
        if ($result ["ret"] == 0) {
            $data ["id"] = $id;
            $task_info = array
            (
                'nns_type'=>'video',
                'nns_name'=>$name,
            );
            $this->add_c2_task($id,CDN_ZTE_SP_FLAG,'',$task_info,$db);
            $this->add_c2_task($id,CDN_HW_SP_FLAG,'',$task_info,$db);
            $result = $this->db_obj->nns_db_result(NNS_ERROR_OK, 'vod add ok', $data);

//			加入标签

            if (!empty($vod_info['show_time'])) {
                $vod_info['year'] = substr(trim($vod_info["show_time"]), 0, 4);
            }

//			新增首字母标签类型
            if ($nns_pinyin != null) {
                $vod_info['initial'] = substr($nns_pinyin, 0, 1);
            }

            $label_inst = new nns_label();
            $label_inst->add_label(
                $id, 0, $vod_info
            );
        }
        return $result;
    }

    /**
     * 点播分片信息添加、修改
     * @param String 对应影片注入ID
     * @param String 来源分片id clip_id
     * @param Array(
    index=”分片序号 0为第1集”  *必要参数
    time_len=“分片长度(秒)”
    name="分片名"
    summary=”分片剧情简介”
    pic=“分片海报”××××××××××××××基础函数未存
    director =“导演,导演,….” (可以搜索字段)
    player =“演员,演员,….” (可以搜索字段)
    total_clicks=“总点击” ××××××××××××××基础函数未存
    month_clicks=“月点击” ××××××××××××××基础函数未存
    week_clicks=“周点击” ××××××××××××××基础函数未存
    day_clicks=“日点击” ××××××××××××××基础函数未存
    update_time=“更新时间” ××××××××××××××基础函数未存
    release_time="上映时间" ××××××××××××××基础函数未存
    )
     * @return String 注入成功后index_id
     * 			FALSE 注入失败
     */
    public function update_clip($asset_id, $clip_id, $params,$params_seekpoint=null,$conf_info=null)
    {
        //echo '<pre>';print_r($params);die();
        //检查是否影片注入ID已存在
        $dc = nl_get_dc(array(
            'db_policy' => NL_DB_WRITE,
            'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
        ));
        $dc->open();
        $import_source = IMPORT_SOURCE;
        if(isset($params['import_source']) && !empty($params['import_source']))
        {
            $import_source = $params['import_source'];
        }
        $params['asset_source'] = (!isset($params['asset_source']) || strlen($params['asset_source']) < 1) ? '0' : $params['asset_source'];
        $video_inst = new nns_db_vod_class();
        $params['asset_source'] =FUSION_FLAG;
        $exists_id = $video_inst->get_video_id_by_import_id(IMPORT_SOURCE, $asset_id,$params['asset_source']);
        if ($exists_id === FALSE)
        {
            $this->import_desc =array(
                'ret'=>6,
                'reason'=>'asset id is not exist',
            );
            return FALSE;
        }
        $vod_index_inst = new nns_db_vod_index_class();
        $vod_index_inst->cp_config = $this->cp_config;
        $exists_is = $vod_index_inst->get_video_index_id_by_import_id($import_source, $clip_id, null, false,false,$params['asset_source']);

        $vod_media_inst = new nns_db_vod_media_class();
        $index = (int)$params['index'];
        $release_time = strtotime($params['release_time']);
        $release_time = date('Y-m-d', $release_time);

        if (is_array($exists_is))
        {
            //查看这个分集的主媒资id是否是和查询出来的id一直,如果一致,则看
            if ($exists_id == $exists_is['nns_vod_id'])
            {
                if ($exists_is['nns_index'] != $index)
                {
                    //如果分集序号不相同,则先要删除原来的分集和片源信息,再添加新的信息
                    $video_index_ary = nl_db_get_one("select * from nns_vod_index where nns_id='{$exists_is['nns_id']}' and nns_deleted!=1", $dc->db());
                    $sql_media = "select * from nns_vod_media where  nns_vod_index_id='{$video_index_ary['nns_id']}' and nns_deleted!=1";
                    $media_ary = nl_db_get_all($sql_media, $dc->db());
                    $data = $video_index_ary;
//                    $data['nns_id'] = np_guid_rand();
                    $data['nns_id'] = $params('guid');
                    $data['nns_vod_id'] = $exists_id;
                    $data['nns_index'] = $index;
                    $data['nns_release_time'] = $release_time;
                    $data['nns_image'] = $params['pic'];
                    $data['nns_update_time'] = $params['update_time'];
                    $data['nns_status'] = 1;
                    $data['nns_action'] = 'add';
                    $data['nns_name'] = $params['name'];
                    $data['nns_time_len'] = $params['time_len'];
                    $data['nns_modify_time'] = date('Y-m-d H:i:s', time());
                    $data['nns_cp_id'] = (isset($params['asset_source']) && strlen($params['asset_source']) >0) ? $params['asset_source'] : '0';
                    $data['nns_summary'] = $this->change_spcial_word($params['summary']);
//                    unset($data['nns_integer_id']);
                    nl_db_insert($dc->db(), 'nns_vod_index', $data);
                    //$vod_index_inst->nns_db_vod_index_delete($exists_is['nns_id']);
                    if (is_array($media_ary))
                    {
                        foreach ($media_ary as $media_key => $media_val)
                        {
                            $data_media = $media_val;
//                            $data_media['nns_id'] = np_guid_rand();
                            $data['nns_id'] = $params['guid'];
                            $data_media['nns_vod_id'] = $exists_id;
                            $data_media['nns_vod_index_id'] = $data['nns_id'];
                            $data_media['nns_vod_index'] = $index;
                            $data_media['nns_modify_time'] = date('Y-m-d H:i:s', time());
                            $data_media['nns_status'] = 1;
                            $data_media['nns_action'] = 'add';
                            $data_media['nns_modify_time'] = date('Y-m-d H:i:s', time());
                            $data_media['nns_cp_id'] = empty($params['asset_source']) ? '0' : $params['asset_source'];
//                            unset($data_media['nns_integer_id']);
                            nl_db_insert($dc->db(), 'nns_vod_media', $data_media);
                        }
                    }

                }
                elseif ($exists_is['nns_index'] == $index)
                {
                    $video_index_ary = nl_db_get_one("select * from nns_vod_index where nns_id='{$exists_is['nns_id']}' and nns_deleted!=1", $dc->db());
                    $data = $video_index_ary;
                    //$data['nns_id'] = np_guid_rand();
                    $data['nns_vod_id'] = $exists_id;
                    $data['nns_index'] = $index;
                    $data['nns_release_time'] = $release_time;
                    $data['nns_image'] = $params['pic'];
                    $data['nns_update_time'] = $params['update_time'];
                    $data['nns_status'] = 1;
                    $data['nns_action'] = 'modify';
                    $data['nns_name'] = $params['name'];
                    $data['nns_modify_time'] = date('Y-m-d H:i:s', time());
                    $data['nns_cp_id'] = (isset($params['asset_source']) && strlen($params['asset_source']) >0) ? $params['asset_source'] : '0';
                    $data['nns_summary'] = $this->change_spcial_word($params['summary']);
                    $data['nns_time_len'] = $params['time_len'];
                    $where = "nns_id='{$exists_is['nns_id']}'";
                    nl_db_update($dc->db(), 'nns_vod_index', $data, $where);
                }
            }
            elseif ($exists_id != $exists_is['nns_vod_id'])
            {
                //echo __LINE__;
                //如果不是相同的主媒资id
                //第一步 需要

                $old_index_ary = nl_db_get_one("select * from nns_vod_index where nns_deleted!=1 and nns_id='{$exists_is['nns_id']}'", $dc->db());
                $odl_media_ary = nl_db_get_all("select * from nns_vod_media where nns_deleted!=1 and nns_vod_id='{$exists_is['nns_vod_id']}' and nns_vod_index_id='{$exists_is['nns_id']}'", $dc->db());
                //$vod_index_inst->nns_db_vod_index_delete($exists_is['nns_id']);
                $data = $old_index_ary;
//                $data['nns_id'] = np_guid_rand();
                $data['nns_id'] = $params['guid'];
                $data['nns_vod_id'] = $exists_id;
                $data['nns_index'] = $index;
                $data['nns_release_time'] = $release_time;
                $data['nns_image'] = $params['pic'];
                $data['nns_update_time'] = $params['update_time'];
                $data['nns_status'] = 1;
                $data['nns_action'] = 'add';
                $data['nns_name'] = $params['name'];
                $data['nns_modify_time'] = date('Y-m-d H:i:s', time());
                $data['nns_time_len'] = $params['time_len'];
                $data['nns_cp_id'] = (isset($params['asset_source']) && strlen($params['asset_source']) >0) ? $params['asset_source'] : '0';
                $data['nns_summary'] = $this->change_spcial_word($params['summary']);
//                unset($data['nns_integer_id']);
                nl_db_insert($dc->db(), 'nns_vod_index', $data);

                if (is_array($odl_media_ary))
                {
                    foreach ($odl_media_ary as $media_key => $media_val)
                    {
                        $data_media = $media_val;
//                        $data_media['nns_id'] = np_guid_rand();
                        $data_media['nns_id'] = $params['guid'];
                        $data_media['nns_vod_id'] = $exists_id;
                        $data_media['nns_vod_index_id'] = $data['nns_id'];
                        $data_media['nns_vod_index'] = $index;
                        $data_media['nns_modify_time'] = date('Y-m-d H:i:s', time());
                        $data_media['nns_status'] = 1;
                        $data_media['nns_action'] = 'add';
                        $data_media['nns_modify_time'] = date('Y-m-d H:i:s', time());
                        $data_media['nns_cp_id'] = (isset($params['asset_source']) && strlen($params['asset_source']) >0) ? $params['asset_source'] : '0';
//                        unset($data_media['nns_integer_id']);
                        nl_db_insert($dc->db(), 'nns_vod_media', $data_media);
                        $vod_media_inst->nns_db_vod_media_delete($media_val['nns_id'],false);
                    }
                }
            }
            $result = array('ret'=>0);
        }else{
//            $vod_index_inst->message_id = $this->message_id;
            $result = $this->nns_db_vod_index_modify($exists_id, $index, $this->change_spcial_word($params['name']), $params['time_len'], $params['pic'], $this->change_spcial_word($params['summary']), $this->change_spcial_word($params['director']), $this->change_spcial_word($params['player']), $import_source, $clip_id, $release_time,$params['asset_source'],$params['integer_id'],$params['guid']);
        }
        /**
         * 梁攀   2015-04-22   分集打点信息添加注入
         */
        //先 删除分集的某一集打点信息
        $this->del_seekpoint($dc, $index, $exists_id);
        if(!empty($params_seekpoint))
        {
            //再添加分集的 打点信息
            if(array_key_exists('1', $params_seekpoint))
            {
                foreach ($params_seekpoint as $value)
                {
                    $this->add_seekpoint($dc, $index, $exists_id, $value["@attributes"]);
                }
            }
            else
            {
                $this->add_seekpoint($dc, $index, $exists_id, $params_seekpoint["@attributes"]);
            }

        }
        if ($result['ret'] == 0)
        {
            $index_info = $vod_index_inst->nns_db_vod_index_info($exists_id, $index);
            $vod_index_other_data = array(
                'nns_watch_focus' => $params['watch_focus'],
            );
            if(!empty($conf_info))
            {
                $vod_index_other_data['nns_conf_info'] = json_encode($conf_info);
            }
            $this->__update_other_data($dc, $index_info['data'][0]['nns_id'], $vod_index_other_data, 'index');
            return $index_info['data'][0]['nns_id'];
        }
        else
        {

            //			错误日志
            $this->write_log('ret:' . $result['ret'] . "\n" . 'asset_id:' . $asset_id . "\n" . 'clip_id:' . $clip_id . "\n" . 'params:' . json_encode($params) . "\n", 'update_clip');
            return FALSE;
        }
    }

    /**
     * 打点信息删除
     * @param object $dc 数据库操作对象
     * @param int $index 分集号
     * @param string $exists_id vod_id
     * @return boolean
     * @author liangpan
     * @date 2015-04-17
     */
    public function del_seekpoint($dc,$index,$vod_id)
    {
        if(empty($vod_id) || $index=='')
        {
            return true;
        }
        $index=(int)$index;
        $sql_del = "delete from nns_vod_index_seekpoint where nns_video_id='{$vod_id}' and nns_video_index='{$index}' ";
        $result_del = nl_execute_by_db($sql_del, $dc->db());
        if(!$result_del)
        {
            $this->write_log('ret:8,reason:delete seekpoint db error,sql:' . $sql_del , 'delete_seekpoint');
            return false;
        }
        return true;
    }

    /**
     * 打点信息添加
     * @param object $dc 数据库操作对象
     * @param int $index 分集号
     * @param string $exists_id vod_id
     * @param array $params 打点信息添加的数组
     * @return null
     * @author liangpan
     * @date 2015-04-17
     */
    public function add_seekpoint($dc,$index,$exists_id,$params)
    {
        $index = (int)$index;
        $sql_query="select count(*) as total from nns_vod_index_seekpoint where nns_video_index='{$index}' and nns_video_id='{$exists_id}' and nns_type='{$params['type']}' and nns_name='{$params['name']}' ";
        $result_query=nl_query_by_db($sql_query, $dc->db());
        if(!$result_query)
        {
            $this->write_log('ret:8' . " db query seekpoint error " . $sql_query , 'query_seekpoint');
            return ;
        }
        if(is_array($result_query) && $result_query[0]['total'] > 0)
        {
            return ;
        }
        $str_id = np_guid_rand();
        //对打点信息的图片ftp处理
        $check_img_index = $this->img_handel($params['img']);
        if (!$check_img_index)
        {
            $this->write_logs(var_export($this->re_code, true), "打点信息图片处理失败");
            return ;
        }
        $check_img_index = $check_img_index === TRUE ? '' : $check_img_index;
        $sql_insert="insert into nns_vod_index_seekpoint (nns_id,nns_video_index,nns_video_id,nns_type,nns_image,nns_begin,nns_end,nns_name) values " .
            "('{$str_id}','{$index}','{$exists_id}','{$params['type']}','{$check_img_index}','{$params['begin']}','{$params['end']}','{$params['name']}')";
        $result_insert=nl_execute_by_db($sql_insert, $dc->db());
        if(!$result_insert)
        {
            $this->write_log('ret:8' . " db insert seekpoint error " . 'sql:'. $sql_insert , 'insert_seekpoint');
        }
        return ;
    }

    public function write_log($log, $method)
    {
        if (!is_dir(dirname(dirname(dirname(__FILE__))) . '/data/log/mgtv/assets_import/'))
        {
            mkdir(dirname(dirname(dirname(__FILE__))) . '/data/log/mgtv/assets_import/', 0777, true);
        }
        $handle = fopen(dirname(dirname(dirname(__FILE__))) . '/data/log/mgtv/assets_import/' . date('Y-m-d') . '.txt', "a");
        fwrite($handle, "################################" . date("H:i:s", time()));

        fwrite($handle, $method . "   \n" . $log . "\r\n");
        fclose($handle);
    }

    /**
     * 修改媒资注入信息
     * @param $dc
     * @param $id 主键GUID
     * @param $params 修改信息 array()
     * @param $type 修改的类型
     */
    private function __update_other_data($dc, $id, $params, $type = 'video')
    {
        if ($id === FALSE || empty($id))
        {
            return FALSE;
        }
        $exist_key = array(
            'video' => array(
                'nns_cp_id',
                'nns_original_id',
                'nns_image0',
                'nns_image1',
                'nns_image2',
                'nns_image_h',
                'nns_image_s',
                'nns_image_v',
                'nns_play_count',
                'nns_tag',
                'nns_watch_focus'

            ),
            'index' => array(
                'nns_cp_id',
                'nns_release_time',
                'nns_original_id',
                'nns_update_time',
                'nns_image',
                'nns_play_count',
                'nns_watch_focus',
                'nns_drm_flag',
                'nns_isintact'
            ),
            'media' => array(
                'nns_cp_id',
                'nns_original_id',
                'nns_ex_url',
                'nns_resolution',
                'nns_file_time_len',
                'nns_file_size',
                'nns_file_coding',
                'nns_drm_flag',
                'nns_drm_encrypt_solution'
            ),
            'live' => array(
                'nns_cp_id',
                'nns_image0',
                'nns_image1',
                'nns_image2',
                'nns_image_h',
                'nns_image_s',
                'nns_image_v',
            ),
            'stream' => array(
                'nns_import_source',
                'nns_asset_import_id',
                'nns_original_id'
            ),
            'asset'=>array(
                'nns_video_img0',
                'nns_video_img1',
                'nns_video_img2',
                'nns_image_h',
                'nns_image_s',
                'nns_image_v',
                'nns_tag'
            )
        );

        switch ($type)
        {
            case 'video':
                $table = 'nns_vod';
                break;
            case 'index':
                $table = 'nns_vod_index';
                break;
            case 'media':
                $table = 'nns_vod_media';
                break;
            case 'live':
                $table = 'nns_live';
                break;
            case 'stream':
                $table = 'nns_live_media';
                break;
            case 'asset':
                $table = 'nns_assists_item';
                break;
            default:
                return;
                break;
        }

        $set = '';
        foreach ($params as $key => $value)
        {
            if (strlen($value) > 0)
            {
                if (in_array($key, $exist_key[$type]))
                    $set .= " {$key}='{$value}',";
            }
        }

        if (empty($set))
            return;

        $set = rtrim($set, ',');
        if ($type == 'asset')
        {
            $sql = 'update ' . $table . ' set ' . $set . ' where nns_video_id=\'' . $id . '\'';
        }
        else
        {
            $sql = 'update ' . $table . ' set ' . $set . ' where nns_id=\'' . $id . '\'';
        }
        return nl_execute_by_db($sql, $dc->db());
    }

    public function nns_db_vod_index_modify($vod_id, $index, $name = null, $time_len = null, $image = null, $summary = null, $nns_director = NULL, $nns_actor = NULL, $import_source = NULL, $import_id = NULL,$nns_release_time=null,$nns_cp_id=null,$nns_integer_id=null,$guid) {
        $nns_actor = np_build_split_string($nns_actor, '/', false);
        $nns_director = np_build_split_string($nns_director, '/', false);
        $result = array();
        $where = "";
        if (!isset($vod_id) || !isset($index)) {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index modify param error');
            return $result;
        }
        if (empty($vod_id)) {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index modify param error');
            return $result;
        }
        if ($index === null && $index === '') {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_ARGS, 'vod index modify param error');
            return $result;
        }
        $index = (int) $index;
        $time_len = (int) $time_len;
        if(strlen($nns_cp_id) <1)
        {
            $nns_cp_id = 0;
        }
        //index exist
        $str_sql = "select nns_id from nns_vod_index where nns_vod_id='$vod_id' and nns_index=$index and nns_deleted!=1";
        $result = $this->db_obj->nns_db_query($str_sql);
        if ($result ["ret"] != 0) {
            return $result;
        }
        if ($this->db_obj->num_rows <= 0) {
            //insert into index
            //生成vod index GUID
            if(!empty($nns_release_time)){
                $nns_release_time = $nns_release_time.' 00:00:00';
            }else{
                $nns_release_time = date('Y-m-d',time()).' 00:00:00';
            }
//            $guid = new Guid ();
//            $index_id = $guid->toString();
            $index_id = $guid;
            $str_sql = "insert into nns_vod_index(nns_id,nns_vod_id,nns_index,nns_name,nns_time_len,nns_image,nns_summary,nns_create_time,nns_modify_time,nns_import_source,nns_import_id,nns_director,nns_actor,nns_status,nns_action,nns_release_time,nns_cp_id,nns_integer_id)values('$index_id','$vod_id',$index,'$name',$time_len,'$image','$summary',now(),now(),'$import_source','$import_id','$nns_director','$nns_actor',1,'add','$nns_release_time','$nns_cp_id','$nns_integer_id')";
            $result = $this->db_obj->nns_db_execute($str_sql);

            if ($result['ret'] == 0) {
                $task_info = array
                (
                    'nns_type'=>'index',
                    'nns_name'=>$name,
                );
                $this->add_c2_task($index_id,CDN_ZTE_SP_FLAG,$vod_id,$task_info);
                $this->add_c2_task($index_id,CDN_HW_SP_FLAG,$vod_id,$task_info);
                //			加入标签
                $label_inst = new nns_label();
                $label_inst->add_label(
                    $index_id, 3, array(
                        'actor' => $nns_actor,
                        'director' => $nns_director
                    )
                );
            }
        } else {
            $guid = $result['data'][0]['nns_id'];
            $img_str = '';
            if (!empty($image)) {
                $img_str .= ",nns_image='$image'";
            }
            if(!empty($nns_release_time)){
                $nns_release_time = $nns_release_time.' 00:00:00';
                $img_str .= ",nns_release_time='$nns_release_time'";
            }
            if(strlen($nns_cp_id) > 0)
            {
                $img_str = ",nns_cp_id='$nns_cp_id'";
            }
            else
            {
                $img_str = ",nns_cp_id='0'";
            }
            //update
            $str_sql = "update nns_vod_index set nns_import_source='$import_source',nns_import_id='$import_id',nns_deleted=0,nns_name='$name',nns_time_len=$time_len ,nns_summary='$summary',nns_modify_time=now()" . $img_str . ",nns_director='$nns_director',nns_actor='$nns_actor',nns_status=2,nns_action='modify' where nns_vod_id='$vod_id' and nns_index=$index";
            $result = $this->db_obj->nns_db_execute($str_sql);
            if ($result['ret'] == 0) {
                $label_inst = new nns_label();
                $label_inst->delete_label(
                    $guid, 3
                );
                $label_inst->add_label(
                    $guid, 3, array(
                        'actor' => $nns_actor,
                        'director' => $nns_director
                    )
                );
            }
        }
        return $result;
    }

    /**
     * 更新或修改片源信息
     * @param String 影片注入ID
     * @param String 分片注入ID
     * @param String 片源注入ID
     * @param Array(
     * 	file_name="片源名称"
    file_type=“片源类型 flv | mp4 | ts” *必要参数
    file_path=“片源物理文件相对路径”
    file_definition=“片源清晰度 hd|std|low”   *默认为std
    file_resolution=“分辨率”800*600  ××××××××××××××基础函数未存
    file_size=“1024”文件大小M  ××××××××××××××基础函数未存
    file_bit_rate=“片源码率”kbps
    file_desc=”文件描述”
    file_time_len="时长"
    file_core_id='core平台ID'
    file_dimensions='2D'  片源维度 标识 2D 3D类型
     * )
     * @return String 注入成功后media_id
     * 			FALSE 注入失败
     */
    public function update_file($asset_id, $clip_id, $file_id, $params)
    {
        $video_inst = new nns_db_vod_class();
//        $params['asset_source'] = (!isset($params['asset_source']) || strlen($params['asset_source']) < 1) ? '0' : $params['asset_source'];
        $params['asset_source'] = FUSION_FLAG;
        $exists_id = $video_inst->get_video_id_by_import_id(IMPORT_SOURCE, $asset_id,$params['asset_source']);
        if ($exists_id === FALSE)
        {
            $this->import_desc =array(
                'ret'=>6,
                'reason'=>'asset id is not exist',
            );
            return FALSE;
        }
        $import_source = IMPORT_SOURCE;
        if(isset($params['import_source']) && !empty($params['import_source']))
        {
            $import_source = $params['import_source'];
        }
        //检查是否分片注入ID已存在
        $video_index_inst = new nns_db_vod_index_class();
        $exists_index = $video_index_inst->get_video_index_id_by_import_id($import_source, $clip_id,null,null,$exists_id,$params['asset_source']);
        if ($exists_index === FALSE)
        {
            $this->import_desc =array(
                'ret'=>7,
                'reason'=>'index id is not exist',
            );
            return FALSE;
        }
        //$media_name=mb_substr($params['file_name'],0,128,"utf-8");

        $video_media_inst = new nns_db_vod_media_class();
        $video_media_inst->message_id = $this->message_id;
        $params['file_definition'] = empty($params['file_definition']) ? 'std' : $params['file_definition'];
        //片源类型
        $params['media_type'] = (isset($params['media_type']) && !empty($params['media_type'])) ? $params['media_type'] : 1;
        $params['original_live_id'] = (isset($params['original_live_id']) && !empty($params['original_live_id'])) ? $params['original_live_id'] : '';
        //片源服务类型
        $params['media_service_type'] = (isset($params['media_service_type']) && !empty($params['media_service_type'])) ? $params['media_service_type'] : '';
        if($this->media_import_module)//片源检测，删掉老数据
        {
            //不同注入ID
            $video_media_inst->get_file_media_check($exists_id, $exists_index, $file_id, $params['file_definition'], $params['file_type'], $params['file_dimensions'],$params['asset_source'],$params['file_bit_rate'],$params['tag'],$params['media_type'],$params['original_live_id'],$params['media_service_type']);
        }
        //检查是否片源注入ID已存在
        $params['index'] = $exists_index['nns_index'];
        $params['asset_id'] = $exists_index['nns_vod_id'];
        $params['clip_id'] = $exists_index['nns_id'];
        $exists_media = $video_media_inst->get_video_media_id_by_import_id_bk($import_source, $file_id, $params,$params['asset_source']);

        if ($exists_media['nns_vod_id'] != $exists_id)
        {
            $exists_media = false;
        }

        //若片源已存在，根据项目情况判断是否反馈注入失败或成功
        if ($exists_media !== FALSE)
        {
            if(defined('NOTIFY_FAIL_ENABLED') && NOTIFY_FAIL_ENABLED)
            {//片源存在反馈注入失败
                $this->import_desc =array(
                    'ret' => 8,
                    'reason'=>'media is already exist',
                );
                return false;
            }
            else if($this->media_import_comm)
            {
                //注入ID存在，进行删除
                $video_media_inst->nns_db_vod_media_delete($exists_media['nns_id'],false);
            }
            elseif ($this->media_import_module_v2 && (empty($exists_media['nns_mode']) || $this->media_mode[$params['file_definition']] >= $this->media_mode[$exists_media['nns_mode']]))//芒果新的片源替换逻辑
            {
                $video_media_inst->nns_db_vod_media_delete($exists_media['nns_id'],false);
            }
            else
            {
                return $exists_media['nns_id'];
            }
        }
        elseif ($this->media_import_module_v2)//芒果新的片源替换逻辑
        {
            $check_module_v2 = $video_media_inst->get_file_media_check($exists_id, $exists_index, $params['file_dimensions'], $params['file_type'],$params['asset_source'],$params['media_type'],$params['original_live_id'],$params['media_service_type']);
            if(empty($check_module_v2['nns_mode']) || $this->media_mode[$params['file_definition']] >= $this->media_mode[$check_module_v2['nns_mode']])
            {
                $video_media_inst->nns_db_vod_media_delete($check_module_v2['nns_id'],false);
            }
        }
        //注入片源时，由于注入ID相同，只是import_source不同，则会造成新增失败，需把片源删除但不生成任务
        if((int)$this->cp_config['check_metadata_enabled'] === 0)
        {
            $this->check_metadata_media($exists_id,$exists_index['nns_id'],$file_id,$params['media_service_type']);
        }

        $result = $this->add_file($video_media_inst, $exists_id, $exists_index, $params, $file_id,$import_source);

        if ($result['ret'] == 0)
        {
            $media_info = $video_media_inst->get_video_media_id_by_import_id_bk($import_source, $file_id, $params);
            $dc = nl_get_dc(array(
                'db_policy' => NL_DB_WRITE,
                'cache_policy' => NP_KV_CACHE_TYPE_MEMCACHE
            ));
            $dc->open();
            nl_vod::delete_vod_info_by_cache($dc, $media_info['nns_vod_id']);
            return $media_info['nns_id'];
        }
        else
        {
            //			错误日志
            $this->write_log('ret:' . $result['ret'] . "\n" . 'asset_id:' . $asset_id . "\n" . 'clip_id:' . $clip_id . "\n" . 'media_id:' . $file_id . "\n" . 'params:' . json_encode($params) . "\n", 'update_media');
            $this->import_desc = $result;
            return FALSE;
        }
    }

    private function add_file($video_media_inst, $exists_id, $exists_index, $params, $file_id,$import_source)
    {
        $result = $this->nns_db_vod_media_add_impl($exists_id, $exists_index['nns_index'], $exists_index['nns_id'], $this->change_spcial_word($params['file_name']), 0, 1, $params['file_definition'], $params['tag'], 1, $params['file_path'], $params['file_bit_rate'], NULL, $params['file_core_id'], NULL, $params['file_type'], 'VOD', $import_source, $file_id, $params['file_dimensions'],$params['asset_source'],$params['media_type'],$params['original_live_id'],$params['start_time'],$params['media_service_type'],'',$params['guid']);
        return $result;
    }

    /**
     * 将基础函数没有插入的数据入片源扩展库
     * @param string 片源注入ID:片源id
     * @param array $params
     */
    public function insert_vod_media_data_ex($media_id, $params = array(),$nns_cp_id=null)
    {
        if (empty($params) || empty($media_id))
        {
            return null;
        }
        $nns_cp_id = (strlen($nns_cp_id) > 0) ? $nns_cp_id : 0;
        $sql_delete = "delete from nns_vod_media_ex where nns_vod_media_id='{$media_id}' and nns_cp_id='{$nns_cp_id}'";
        nl_execute_by_db($sql_delete, $this->dc->db());
        $val = "";
        foreach ($params as $key => $v)
        {
            if (!empty($v))
            {
                $val .= "('{$media_id}','{$key}','{$v}','{$nns_cp_id}'),";
            }
        }
        if(empty($val)) return;
        $val = trim($val, ',');
        $sql = "insert into nns_vod_media_ex(nns_vod_media_id,nns_key,nns_value,nns_cp_id) values{$val}";
        return nl_execute_by_db($sql, $this->dc->db());
    }

    public function update_media_data($media_id, $params = null,$nns_cp_id=null)
    {

        if (empty($params))
        {
            return false;
        }
        foreach ($params as $key => $v)
        {
            $set .= "nns_{$key}='{$v}',";
        }
        $str_update = (strlen($nns_cp_id) > 0 ) ? " and nns_cp_id='{$nns_cp_id}' " : " and nns_cp_id='0' ";
        $set = trim($set, ',');
        $sql = "update nns_vod_media set {$set} where nns_id='{$media_id}' {$str_update}";
        return nl_execute_by_db($sql, $this->dc->db());

    }

    /**
     * 将基础函数没有插入的数据入分集扩展库
     * @param string 分集注入ID:影片id
     * @param array $params
     */
    public function insert_vod_index_data_ex($index_id, $params = array(),$nns_cp_id=null)
    {
        if (empty($params) || empty($index_id))
        {
            return null;
        }
        $nns_cp_id = (strlen($nns_cp_id) > 0) ? $nns_cp_id : 0;
        $sql_delete = "delete from nns_vod_index_ex where nns_vod_index_id='{$index_id}' and nns_cp_id='{$nns_cp_id}'";
        nl_execute_by_db($sql_delete, $this->dc->db());
        $val = "";
        foreach ($params as $key => $v)
        {
            if (!empty($v))
            {
                $val .= "('{$index_id}','{$key}','{$v}','{$nns_cp_id}'),";
            }
        }
        if(empty($val)) return;
        $val = trim($val, ',');
        $sql = "insert into nns_vod_index_ex(nns_vod_index_id,nns_key,nns_value,nns_cp_id) values{$val}";
        return nl_execute_by_db($sql, $this->dc->db());
    }

    /**
     * 需要改写影片信息 BY S67 2013-04-30
     * 1. MGTV的影片长度保存在分片信息中,需要重写。
     * 2. MGTV的影片上映时间？？？？
     * @param string $video_id:影片id
     * @param array $params {
    "view_len":时长，秒
    }
     */
    public function modify_vod_other_data($video_id, $params = array())
    {
        if (empty($params) || empty($video_id))
        {
            return null;
        }
        $set = "";
        foreach ($params as $key => $v)
        {
            $set .= "nns_{$key}='{$v}',";
        }
        $set = trim($set, ',');
        $sql = "update nns_vod set {$set} where nns_id='{$video_id}' OR nns_asset_import_id='{$video_id}'";
        return nl_execute_by_db($sql, $this->dc->db());
    }

    /**
     * 将基础函数没有插入的数据入vod表
     * @param string $video_id:影片id
     * @param array $params
     */
    public function insert_vod_data($video_id, $params = array(),$nns_cp_id = null)
    {
        if (empty($params) || empty($video_id))
        {
            return null;
        }
        $set = "";
        foreach ($params as $key => $v)
        {
            if(strpos($key , 'image') !== false && empty($v))
            {
                continue;
            }
            else
            {
                $set .= "nns_{$key}='{$v}',";
            }
        }
        $set = trim($set, ',');
//        $str_where  = (strlen($nns_cp_id) > 0) ? " and nns_cp_id ='{$nns_cp_id}' " : " and nns_cp_id ='0' ";
        $tem_cp_id = FUSION_FLAG;
        $str_where  =  " and nns_cp_id ='{$tem_cp_id}' ";
        //$sql = "update nns_assists_item as a,nns_vod as v set a.nns_video_img2='{$params['image2']}',a.nns_play_count='{$params['play_count']}' where a.nns_video_id=v.nns_id and (v.nns_id='{$video_id}' or v.nns_asset_import_id='{$video_id}')";
        // nl_execute_by_db($sql, $this->dc->db());
        $sql = "update nns_vod set {$set} where (nns_id='{$video_id}' OR nns_asset_import_id='{$video_id}') {$str_where} ";
        return nl_execute_by_db($sql, $this->dc->db());
    }

    /**
     * 将基础函数没有插入的数据入扩展库
     * @param string $video_id:影片注入id
     * @param array $params
     */
    public function insert_vod_data_ex($video_id, $params = array(),$nns_cp_id = null)
    {
        if (empty($params) || empty($video_id))
        {
            return null;
        }
        $nns_cp_id = (strlen($nns_cp_id) > 0 ) ? $nns_cp_id : 0;
        $sql_delete = "delete from nns_vod_ex where nns_vod_id='{$video_id}' and nns_cp_id='{$nns_cp_id}'";
        nl_execute_by_db($sql_delete, $this->dc->db());
        $val = "";
        foreach ($params as $key => $v)
        {
            if (!empty($v))
            {
                $val .= "('{$video_id}','{$key}','{$v}','{$nns_cp_id}'),";
            }
        }
        if(empty($val)) return;
        $val = trim($val, ',');
        $sql = "insert into nns_vod_ex(nns_vod_id,nns_key,nns_value,nns_cp_id) values{$val}";
        return nl_execute_by_db($sql, $this->dc->db());
    }

    public function nns_db_vod_media_add_impl($vod_id, $index, $index_id, $media_name, $state, $check, $mode, $tag, $type, $url, $stream, $http_url,
                                              $contentid, $ret, $file_type,$media_caps='VOD',$import_source=NULL,$import_id=NULL,$dimens='0',$nns_cp_id=null,$media_type=1,
                                              $original_live_id='',$start_time='',$media_service_type='',$nns_dmain='',$guid)
    {
        if ($dimens=='0' || $dimens=='')
        {
            $dimens_str=" and (nns_dimensions='0' or nns_dimensions='') ";
        }
        else
        {
            $dimens_str=" and nns_dimensions='$dimens' ";
        }
        if(strlen($stream) > 0)
        {
            $stream_str=" and nns_kbps='$stream' ";
        }
        if(strlen($nns_cp_id) <1)
        {
            $nns_cp_id = 0;
        }
        //片源类型 1 点播  2回看
        if(strlen($media_type) > 0)
        {
            $m_type_str = " and nns_media_type='{$media_type}' ";
        }
        //频道原始ID,回看点播源存在
        if(strlen($original_live_id) > 0)
        {
            $o_live_str = " and nns_original_live_id='{$original_live_id}' ";
        }
        //片源服务类型
        if(strlen($media_service_type) > 0)
        {
            $s_type_str = " and nns_media_service='{$media_service_type}' ";
        }
        $str_sql = "select 1 from nns_vod_media where nns_deleted=0 and nns_vod_id='$vod_id' and nns_vod_index_id='$index_id' and nns_mode='$mode' and nns_filetype='$file_type' and nns_cp_id='$nns_cp_id' {$dimens_str} {$stream_str} {$m_type_str} {$o_live_str} {$s_type_str} ";
        if ($tag !== null && $tag !== '')
        {
            $str_sql .= "  and nns_tag='$tag'";
        }
        $result = $this->db_obj->nns_db_query($str_sql);
        if ($result ["ret"] != 0)
        {
            return $result;
        }
        if ($this->db_obj->num_rows > 0)
        {
            $result = $this->db_obj->nns_db_result(NNS_ERROR_VOD_MEDIA_EXIST, 'vod media exist');
            return $result;
        }
//        $guid = new Guid ();
//        $media_id = $guid->toString ();
        $media_id = $guid;
        $nns_integer_id = substr($guid,6,7);
        $ret=(int) $ret;
        $nns_media_name = $this->get_file_name($url);
        if($media_service_type == 'hw')
        {
            $str_sql = "insert into nns_vod_media(nns_id,nns_name,nns_vod_id,nns_vod_index,nns_vod_index_id,nns_state,nns_check,nns_tag,nns_type,nns_url,
            nns_mode,nns_kbps,nns_create_time,nns_modify_time,nns_deleted,nns_content_id,nns_content_state,nns_filetype,nns_media_caps,nns_import_source,
            nns_import_id,nns_dimensions,nns_status,nns_action,nns_cp_id,nns_media_name,nns_media_type,nns_original_live_id,nns_start_time,
            nns_media_service,nns_domain)values('$media_id','$media_name','$vod_id',$index,'$index_id',$state,$check,'$tag',$type,'$url','$mode','$stream',now(),
            now()," . NNS_VOD_MEDIA_DELETED_FALSE . ",'$contentid','$ret','$file_type','$media_caps','$import_source','$import_id','{$dimens}',1,'add',
            '$nns_cp_id','{$nns_media_name}','{$media_type}','{$original_live_id}','{$start_time}','{$media_service_type}','{$nns_dmain}')";
        }
        if($media_service_type == 'zte')
        {
            $str_sql = "insert into nns_vod_media(nns_id,nns_name,nns_vod_id,nns_vod_index,nns_vod_index_id,nns_state,nns_check,nns_tag,nns_type,nns_url,
            nns_mode,nns_kbps,nns_create_time,nns_modify_time,nns_deleted,nns_content_id,nns_content_state,nns_filetype,nns_media_caps,nns_import_source,
            nns_import_id,nns_dimensions,nns_status,nns_action,nns_cp_id,nns_media_name,nns_media_type,nns_original_live_id,nns_start_time,
            nns_media_service,nns_domain,nns_integer_id)values('$media_id','$media_name','$vod_id',$index,'$index_id',$state,$check,'$tag',$type,'$url','$mode','$stream',now(),
            now()," . NNS_VOD_MEDIA_DELETED_FALSE . ",'$contentid','$ret','$file_type','$media_caps','$import_source','$import_id','{$dimens}',1,'add',
            '$nns_cp_id','{$nns_media_name}','{$media_type}','{$original_live_id}','{$start_time}','{$media_service_type}','{$nns_dmain}','{$nns_integer_id}')";
        }
        $result = $this->db_obj->nns_db_execute ( $str_sql );
        if ($result ["ret"] != 0 && !empty($contentid))
        {
            return $result;
        }
        $task_info = array
        (
            'nns_type'=>'media',
            'nns_name'=>$media_name,
        );
        if($media_service_type=='hw')
        {
            $sp_id_media = CDN_HW_SP_FLAG;
        }
        if($media_service_type=='zte')
        {
            $sp_id_media =CDN_ZTE_SP_FLAG;
        }
        $this->add_c2_task($media_id,$sp_id_media,$index_id,$task_info);
        //更新第几集
        $str_sql = "update nns_vod set nns_new_index=$index,nns_status=2,nns_action='modify',nns_modify_time=now() where nns_id='$vod_id' and nns_cp_id='$nns_cp_id'";
        $this->db_obj->nns_db_execute ( $str_sql );
        $result["nns_id"]=$media_id;
        return $result;
    }

    /**
     * 获取片源路径的文件名称
     * @param string $url
     * @return string
     * @author liangpan
     * @date 2016-08-27
     */
    public function get_file_name($url)
    {
        $url = trim($url);
        if(strlen($url) < 1)
        {
            return '';
        }
        $pathinfo_file = pathinfo(basename($url));
        $file_name=$pathinfo_file['filename'];
        $file_name = strtolower(str_replace(array('_','.'), '', $file_name));
        return strlen($file_name)< 1 ? '' : $file_name;
    }

    public function check_metadata_media($vod_id,$index_id,$media_import_id,$media_service_type)
    {
        $check_sql = "select nns_id from nns_vod_media where nns_deleted=0 and nns_vod_id='{$vod_id}' and nns_vod_index_id='{$index_id}' and nns_import_id='{$media_import_id}' and nns_media_service='{$media_service_type}'";
        $result = $this->db_obj->nns_db_query($check_sql);
        if ($result['ret'] == 0 && count($result['data']) > 0)
        {
            foreach ($result['data'] as $val)
            {
                $this->nns_db_vod_media_delete($val['nns_id'],false);
            }
        }
    }

    /**
     * 生成C2队列
     */
    public function add_c2_task($id,$sp_id,$nns_parent_id='',$task_info)
    {
        //如果获取的操作队列动作为删除或者c2没有注入，则将转台修改为添加
        $guid = np_guid_rand($sp_id);
        $sql_c2task = "insert into nns_mgtvbk_c2_task(nns_id,nns_type,nns_name,nns_ref_id,nns_action,nns_status,nns_create_time,nns_org_id,nns_src_id,nns_clip_task_id,nns_clip_date,nns_op_id,nns_epg_status) values ('$guid','{$task_info['nns_type']}','{$task_info['nns_name']}','$id','".BK_OP_ADD."','0',now(),'$sp_id','$nns_parent_id',null,null,null,'99')";
        $this->db_obj->nns_db_execute($sql_c2task);
    }
}